import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios'

// 可根据需要自定义 API 返回结构；当前后端直接返回数据列表/对象，直接透传 data 即可
export type HttpResult<T = unknown> = Promise<T>

const instance: AxiosInstance = axios.create({
  baseURL: '/api', // 结合 Vite 代理，将会被转发到后端 8080，并去掉 /api 前缀
  timeout: 15000,
  withCredentials: false,
})

// 请求拦截：注入鉴权等
instance.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers = config.headers || {}
    ;(config.headers as Record<string, string>)['Authorization'] = `Bearer ${token}`
  }
  return config
})

// 响应拦截：统一错误处理
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data
  },
  (error) => {
    // 这里可做统一错误提示、上报等
    // eslint-disable-next-line no-console
    console.error('HTTP Error:', error?.response?.status, error?.message)
    return Promise.reject(error)
  },
)

// 基础方法封装（保留原始 config 能力）
function get<T = unknown>(url: string, config?: AxiosRequestConfig): HttpResult<T> {
  return instance.get(url, config)
}

function post<T = unknown>(url: string, data?: unknown, config?: AxiosRequestConfig): HttpResult<T> {
  return instance.post(url, data, config)
}

function put<T = unknown>(url: string, data?: unknown, config?: AxiosRequestConfig): HttpResult<T> {
  return instance.put(url, data, config)
}

function del<T = unknown>(url: string, config?: AxiosRequestConfig): HttpResult<T> {
  return instance.delete(url, config)
}

export const request = { get, post, put, delete: del }
export default request
export { instance as axiosInstance }

